package org.example.opus.controller;


import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.example.ai.model.entity.Works;
import org.example.ai.result.ResultCodeEnum;
import org.example.ai.util.AuthContextHolder;
import org.example.opus.login.RedisTokenLookup;
import org.example.opus.service.IWorksService;
import org.example.ai.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 作品表，存储用户发布的作品信息及相关属性 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-17
 */
@RestController
@Slf4j
@RequestMapping("/works")
public class WorksController {

    @Autowired
    private IWorksService worksService;

//    @Operation(summary = "作品列表")
//    @GetMapping("/worksList")
//    public List<Works> worksList(@RequestBody Works works){
//        return worksService.worksList(works);
//    }

    @Operation(summary = "获取作品")
    @GetMapping("/getWork")
    @RedisTokenLookup
//    public Result getWork(){
//        Long userId = AuthContextHolder.getUserId();
//
//        if (userId == null) {
//            // 处理用户ID为空的情况，例如返回错误信息或抛出自定义异常
//            System.out.println("用户ID为空");
//        }
//
//        Integer id = Math.toIntExact(userId);
//        List<Works> works = worksService.getWork(id);
//        return Result.ok(works);
//    }

    public Result getWork() {
        Long userId = AuthContextHolder.getUserId();

        if (userId == null) {
            // 用户ID为空，返回错误信息
            System.out.println("用户ID为空");
            return Result.build("用户未登录或令牌无效", ResultCodeEnum.FAIL);
        }

        try {
            Integer id = Math.toIntExact(userId);
            List<Works> works = worksService.getWork(id);
            return Result.ok(works);
        } catch (ArithmeticException e) {
            // 处理可能的溢出异常
            return Result.build("用户ID超出Integer范围", ResultCodeEnum.FAIL);
        }
    }



    @Operation(summary = "作品删除")
    @DeleteMapping("/getWorkDelete/{workId}")
    public Result getWorkDelete(@PathVariable Integer workId){
        boolean del = worksService.removeById(workId);
        return Result.ok(del);
    }

    @Operation(summary = "作品详情")
    @GetMapping("/getAllWorks/{workId}")
    public Works getAllWorks(@PathVariable Integer workId){
        return worksService.getAllWorks(workId);
    }

    @Operation(summary = "添加作品")
    @PostMapping ("/getWorkAdd")
    public Works getWorkAdd(@RequestBody Works works){
        return worksService.getWorkAdd(works);
    }


    @Operation(summary = "查数据")
    @PostMapping("/getWorkList")
    public Works getWorkList(@RequestBody Integer workId){
        return worksService.getWorkList(workId);
    }

}
